package com.lkm.app_ui.m.Imple.vip;

import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.help.BeepManager;
import com.lkm.app_ui.m.fun.OnNfcDataEvent;
import com.lkm.app_ui.m.nfc.NFC_Module;
import com.lkm.app_ui.m.vip.VipModule;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.task.ProgressDataImpl;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.javatool.StringHelp;



class LooperReadNfcData {



    private Handler mainHandler;


    public LooperReadNfcData() {


        mainHandler = new Handler(Looper.getMainLooper());
    }

    public void start() {
        readNfc();
    }

    private void readNfc() {
        NFC_Module nfc_module = AppConst.getModuleManager().peekModule(NFC_Module.class);
        Task<Object, Object, String> task =nfc_module==null?null: nfc_module.waitReadVipInfo();

        if(task!=null&&task.getSerialNum()!=Task.serialNum_not) {
            task.addBackCall(new BackCallAdapter<Object, String>() {
                @Override
                protected void onEnd(Task<?, Object, String> task, String s, boolean isCancel) {
                    super.onEnd(task, s, isCancel);
                    postRead();
                    onInputStr(s);
                }

            });
        }else {
            postRead();
        }
    }
    private static BeepManager beepManager;
    private void onInputStr(String cardNo) {
        if (!StringHelp.isEmpty(cardNo)) {
            LinkBus.sendBroadcast(new OnNfcDataEvent(cardNo));


            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (beepManager == null) {
                            beepManager = new BeepManager(BaseFragmentActivity.getLastActivity(),com.google.zxing.client.android.R.raw.beep);
                            beepManager.updatePrefs();
                        }
                        beepManager.playBeepSoundAndVibrate();
                    } catch (Exception e) {
                        beepManager = null;
                    }
                }
            });


//            Toast toast = Toast.makeText(BaseFragmentActivity.getLastActivity(), cardNo, Toast.LENGTH_LONG);

//            VipModule vipModule = AppConst.getModuleManager().peekModule(VipModule.class);


        }
    }


    void postRead() {
        mainHandler.removeCallbacksAndMessages(null);
        mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                readNfc();
            }
        }, 1000);
    }


}
